require "Config.NetSystemMsgDefine"
local NetCustomMsgHook = require "NetworkLogic.NetCustomMsgHook"

--进入这里的参数，都已经在网络流上取出了消息的ID（总的，不是custom的）
local SystemMsgHandler = {}

-- Handle SERVER_ERROR_CODE
SystemMsgHandler[SERVER_ERROR_CODE] = 
function(s) 
    Debug.Log("Process SERVER_ERROR_CODE")
end

-- Handle SERVER_VALID_ACC
SystemMsgHandler[SERVER_VALID_ACC] = 
function(s) 
    assert(s:len() == 1)
    print (s:byte())
    local result = string.unpack('b', s)
    
    if result == 0 then
        print ('收到网络消息，result = ' .. result)

        NetStreamEncoder:init()
        local bytes = NetStreamEncoder:formatToStructStream()
        NetworkManager:SendSystemMsg(3, bytes)
    else
        print ('网络消息返回错误值，result = ' .. result)
    end
end

-- Handle SERVER_LOGIN
SystemMsgHandler[SERVER_LOGIN] = 
function(s) 
    assert(s:len() == 9)
    for i=1, s:len(), 1 do
        print (s:byte())
    end

    local result = string.unpack('b', s)
    local userId = string.unpack('j', s:sub(2))
    
    if result == 0 then
        print("收到login结果。userId = " .. userId )

        -- Login in to lobby
        NetStreamEncoder:init()
        NetStreamEncoder:pushLong(userId)
        NetStreamEncoder:pushDWord(1)
        NetStreamEncoder:pushWString('unknown ChannelId')
        NetStreamEncoder:pushWString('1.0.1')
        NetStreamEncoder:pushWString('unknown eviceId')
        NetStreamEncoder:pushWString('unknown osVersion')
        NetStreamEncoder:pushWString('unknown MobileModel')
        NetStreamEncoder:pushWString('unknown Provider')
        NetStreamEncoder:pushWString('unknown netType')
        NetStreamEncoder:pushWString('')
        NetStreamEncoder:pushWString('1122')
        NetStreamEncoder:pushWString('3344')
        NetStreamEncoder:pushWString('5566')
        NetStreamEncoder:pushWString('2')
        local stream = NetStreamEncoder:formatToStructStream()
        NetworkManager:SendSystemMsg(4, stream)
    else
        print ('网络消息返回错误值，result = ' .. result)
    end
end

-- Handle SERVER_LOGIN_LOBBY
SystemMsgHandler[SERVER_LOGIN_LOBBY] = 
function(s) 
    print('Login in to lobby')
end

-- Handle SERVER_PROPERTY_TABLE
SystemMsgHandler[SERVER_PROPERTY_TABLE] = 
function(s) 
    local count = string.unpack('h', s)

    local index = 3
    for i = 1, count, 1 do
        local propName, ignoreLen = CS.FitFun.StringConvert.UTF16StreamToString(s:sub(index), true)
        index = index + ignoreLen
        print (propName)
        local propType = string.unpack('b', s:sub(index))
        index = index + 1
        print (propType)
    end
end

-- Handle SERVER_CUSTOM
SystemMsgHandler[SERVER_CUSTOM] = 
function(s) 
    local unitCount = string.unpack('h', s)
    local firstUnitType = string.unpack('b', s:sub(3))
    assert(firstUnitType == 2)
    local customMsgId = string.unpack('l', s:sub(4))

    local unitList = NetStreamDecoder:parseFrom(s:sub(8))
    NetCustomMsgHook:process(customMsgId, unitList)
end

return SystemMsgHandler